<template>
  <div>
    {{ res }}
    <h2>echarts图表</h2>
    <div id="box" ref="charts"></div>

  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, defineProps, watch } from 'vue'
import * as echarts from 'echarts';

// 获取图表DOM元素
let charts = ref(null)

// 图表实例
let myChart = ref(null)

// 接受父组件传递的参数
const props = defineProps(['res'])

// 接受数据项
const setOptions = ref(null)

onMounted(() => {
  // 基于准备好的dom，初始化echarts实例

  initEcharts()

})

watch(() => props.res, (val) => {
  console.log(val)

  let { xAxis, legend, series } = val[0]

  let aa = setSeriesData(series)

  console.log(aa,'1111')

  setOptions.value = {
    title: {
      text: '图表数据实时更新'
    },
    tooltip: {
      trigger: 'axis'
    },
    containLabel: true,
    smooth: true,
    xAxis: xAxis,
    yAxis: {
      type: 'value'
    },
    legend: legend,
    series:series
  }
  // 绘制图表
  myChart.setOption(setOptions.value)

},{deep:true})

//定义初始化方法
function initEcharts() {
  myChart = echarts.init(charts.value);
}

// 设置 series 数据
function setSeriesData(data) {

  let SeriesData = []
  for (let i = 0; i < data.length; i++) {

    // console.log(data[i])
    let seriesDataItem = {
      name: data[i].name,
      type: 'line',
      stack: 'Total',
      smooth: true,
      symbol: 'none',
      data: data[i]
    }
    SeriesData.push(seriesDataItem)
  }
  return SeriesData


}



</script>

<style  scoped>
#box {
  width: 800px;
  height: 400px;
}
</style>
